package org.mech.sefer.client.mvp;

import java.util.ArrayList;
import java.util.List;

import org.mech.sefer.event.Handler;
import org.mech.sefer.event.bus.EventBus;
import org.mech.sefer.event.register.HandlerRegistration;
import org.mech.sefer.event.register.HandlerRegistrationInfo;

/**
 * <p>
 * The AbstractPresenter is abstract implementation of presenter
 * </p>
 * <p>
 * Date: 24.4.2012 12:32:10
 * </p>
 * 
 * @param <V>
 *            the value type
 * @author martin.krajc
 */
public abstract class AbstractPresenter<V extends View> implements Presenter<V> {
	private V view;
	private EventBus eventBus;
	private List<HandlerRegistration> handlerRegistrations;

	public AbstractPresenter() {
		super();
		handlerRegistrations = new ArrayList<HandlerRegistration>();
	}

	@Override
	public V getView() {
		return view;
	}

	@Override
	public EventBus getEventBus() {
		return eventBus;
	}

	@Override
	public final void bind() {
		onBind();
	}

	@Override
	public final void unbind() {
		for (HandlerRegistration handlerRegistration : handlerRegistrations) {
			handlerRegistration.unregister();
		}
		onUnbind();
	}

	/**
	 * On bind.
	 */
	protected void onBind() {
	};

	/**
	 * On unbind.
	 */
	protected void onUnbind() {
	}

	/**
	 * Sets the view.
	 * 
	 * @param view
	 *            the new view
	 */
	public void setView(V view) {
		this.view = view;
	}

	/**
	 * Sets the event bus.
	 * 
	 * @param eventBus
	 *            the new event bus
	 */
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	};

	/**
	 * Register handler on presenter. On unbind the registration will properly
	 * unregister.
	 * 
	 * @param eventClass
	 *            the event class
	 * @param handler
	 *            the handler
	 * @param info
	 *            the registration info
	 */
	public void registerHandler(Class<?> eventClass, Handler handler,
			HandlerRegistrationInfo info) {
		handlerRegistrations.add(getEventBus().registerHandler(eventClass,
				handler, info));
	}

	/**
	 * Register handler on presenter. On unbind the registration will properly
	 * unregister.
	 * 
	 * @param eventClass
	 *            the event class
	 * @param handler
	 *            the handler
	 */
	public void registerHandler(Class<?> eventClass, Handler handler) {
		handlerRegistrations.add(getEventBus().registerHandler(eventClass,
				handler));
	}

}
